<template>
	<view>
		<view class="card">
			<uni-forms ref="merchantConfiguration"  :rules="rules" :modelValue="form" label-position="top">
				<uni-forms-item label="商家姓名" name='merchantName' required labelWidth="180px">
					<uni-easyinput v-model="form.merchantName" placeholder="请输入商家姓名" />
				</uni-forms-item>

				<uni-forms-item label="商家电话" name="merchantPhone" required labelWidth="180px">
					<uni-easyinput v-model="form.merchantPhone" placeholder="请输入商家电话" />

				</uni-forms-item>
				<uni-forms-item label="商家地址" name="merchantAddress" required labelWidth="180px">
					<uni-easyinput @focus="merchantAddressFn" suffixIcon="location-filled"
						v-model="form.merchantAddress" placeholder="请输入商家地址" />

				</uni-forms-item>
				<uni-forms-item label="联系人" name="contactPerson" required labelWidth="180px">
					<uni-easyinput v-model="form.contactPerson" placeholder="请输入联系人" />

				</uni-forms-item>


				<uni-forms-item label="营业时间" name="businessHoursStart"  required labelWidth="180px">
					<!-- <uni-easyinput :styles="styles" suffixIcon="calendar" class="selectTime"
							v-model="form.businessHours" disabled placeholder="请输入营业时间" /> -->
					<uni-datetime-picker :value="Date" @change='businessHoursFn' v-model="dateRange"
						type="datetimerange" rangeSeparator="至" />
				</uni-forms-item>
            

				<uni-forms-item label="商家封面图"  required labelWidth="180px">
					<sunui-upimg1 :border="'1px dashed #bfbfbf'" :formData="imgFormData" :storageMode="storageMode"
						:header="header" :size="['200rpx', '200rpx']" btnName="上传图片" :uploadServerUrl="upPicUrl"
						ref="selectimgandupload1" @uploaded="imgLoaded1" @change="imgsChange1"
						:maxFileNumber="1"><template v-slot:icon>
							<uni-icons type="camera-filled" color="#1890FF" size="40"></uni-icons>
						</template></sunui-upimg1>

				</uni-forms-item>
				<uni-forms-item label="商家logo" required labelWidth="180px">
					<sunui-upimg1 :border="'1px dashed #bfbfbf'" :formData="imgFormData" :storageMode="storageMode"
						:header="header" :size="['200rpx', '200rpx']" btnName="上传图片" :uploadServerUrl="upPicUrl"
						ref="selectimgandupload2" @uploaded="imgLoaded2" @change="imgsChange2"
						:maxFileNumber="1"><template v-slot:icon>
							<uni-icons type="camera-filled" color="#1890FF" size="40"></uni-icons>
						</template></sunui-upimg1>

				</uni-forms-item>
				<uni-forms-item label="商家详情图" required labelWidth="180px">
					<sunui-upimg1 :border="'1px dashed #bfbfbf'" :formData="imgFormData" :storageMode="storageMode"
						:header="header" :size="['200rpx', '200rpx']" btnName="上传图片" :uploadServerUrl="upPicUrl"
						ref="selectimgandupload3" @uploaded="imgLoaded3" @change="imgsChange3"
						:maxFileNumber="5"><template v-slot:icon>
							<uni-icons type="camera-filled" color="#1890FF" size="40"></uni-icons>
						</template></sunui-upimg1>

				</uni-forms-item>
			</uni-forms>

			<view class="sumbit-btn flex" @click.stop="uploadQualificationFn('merchantConfiguration')">
				保存信息
			</view>
		</view>
	</view>
</template>

<script>
	import {
		object2Url
	} from '@/utils/trans';
	export default {
		data() {
			return {
				form: {
					// 商家名称
					merchantName: '',
				
					// 商家地址
					merchantAddress: '',
					// 商家电话
					merchantPhone: '',
					// 联系人
					contactPerson: '',
					// 商家封面图
					merchantSurfaceDrawing: '',
					// 商家logo
					merchantLogo: '',
					// 商家详情图
					merchantDetailChart: '',
					id: '',
					// 开始时间
					businessHoursStart:'',
					// 结束时间
					businessHoursEnd:'',
					// 经度
					longitude:'',
					// 经度
					latitude:'',
					


				},
				rules: {
					// 活动名称
					merchantName: {
						rules: [{
							required: true,
							errorMessage: '商家名称不能为空'
						}]
					},
					// 活动说明
					merchantAddress: {
						rules: [{
							required: true,
							errorMessage: '商家地址不能为空'
						}]
					},
					merchantPhone: {
						rules: [{
							required: true,
							errorMessage: '商家电话不能为空'
						}]
					},
					contactPerson: {
						rules: [{
							required: true,
							errorMessage: '联系人不能为空'
						}]
					},
					
					},
					
				storageMode: 2,
				photos: 'http://tmp/oPvxqRtPPstDa128a34f30dbb644483d8ec6e94e75c9.jpg',
				upPicUrl: '',
				imgFormData: null,
				
				alyOssSignatureInfo: null,
				header: null,
				timeDate: '',
				suffix: '',
				imgViewArr: [],
				imgStr1: [],
				imgStr2: [],
				imgStr3: [],
				img: [],
				img2: [],
				img3: [],
				styles: {
					color: '#2979FF',
					borderColor: '#2979FF'
				},
				// 商家信息
				// merchantInformation:'',
				merchantId: 476,
				isUpdata:false,
				ossInfo:null,
				lat:'',
				lng:'',
				dateRange:[]
				
			
			}
		},
		onLoad() {
			this.query()
		},
		methods: {
			async query() {

				const reuslt = await this.$http.post({
					url: this.$api.getMerchantinfo,
					data: {
						id: this.merchantId
					}
				})

				if (reuslt.code == 2000) {
					console.log(reuslt.data)
					this.$sun.assignObject(this.form, {
						...reuslt.data
					})
					// this.merchantInformation = reuslt.data
					console.log(this.merchantInformation)
					this.dateRange=[reuslt.data.businessHoursStart,reuslt.data.businessHoursEnd]
					
					this.isUpdata = true;
				} else {
					this.isUpdata = false;
				}

				this.init()
				// let dateRangeArray = dateRangeString.split('", "');

				// // 去除每个日期字符串的引号
				// dateRangeArray = dateRangeArray.map(date => date.replace(/"/g, ''));

				// console.log(dateRangeArray);

			},
			handleEffectiveFn(e) {
				console.log(e.detail.value)
				this.form.businessHours = e.detail.value
			},
			async uploadQualificationFn(formName) {
			
				// this.$refs[formName].validate((err, formData) => {
				
				// }).then(async res => {
					
				
				// })
				
			 console.log(this.form)
			// 	let getUrl
			// 	if(this.isUpdata){
			// 		getUrl=this.$api.updateMerchantinfo 
			// 	}else{
			// 		getUrl = this.$api.addMerchantinfo
			// 	}
			// 	 	console.log(this.form)
			// 	const result = await this.$http.post({
			// 		url: getUrl,
			// 		data: {
			// 			...this.form
			// 		}
			// 	})
				
			
			// 	if(result.code==2000){
			// 		 this.$sun.toast(result.msg);
			// 		 this.query()
			// 	}else{
				
			// 		uni.showModal({
			// 			content: "操作失败==>" + result.msg,
			// 			showCancel: false,
			// 			confirmText: '确定',
			// 			success() {
					
			// 			}
			// 		})
			// 	}
				
				
			},
			 merchantAddressFn() {
				uni.getLocation({
					// 将wgs84 改为 gcj02  h5提高精确度
					type: 'gcj02',
					//  geocode: true,   address：地址信息（仅App端支持，需配置geocode为true）
					success: res => {
						this.lat = res.latitude;
						this.lng = res.longitude;
						// 获取当前经纬度  存缓存  在计算差距离的时候 调用
						wx.setStorageSync('lat', this.lat);
						wx.setStorageSync('lng', this.lng);
						this.getLocations()
					},
					fail: res => {
						this.lat = res.latitude;
						this.lng = res.longitude;
					}
				});
			},
			getLocations() {
				console.log(this.lat,this.lng)

				uni.chooseLocation({
					success: res => {
						this.form.merchantAddress = res.name;
						this.form.latitude = res.latitude;
						this.form.longitude = res.longitude;
						console.log('获取定位信息res============', res);
					}
				});

			},
			businessHoursFn(e) {
				console.log(e)
			
				// this.  e.businessHoursStart
				// 提取小时和分钟部分
				// const timeArray = e.map(dateString => {
				// 	const date = new Date(dateString);
				// 	const hours = String(date.getHours()).padStart(2, '0'); // 将小时格式化为两位数
				// 	const minutes = String(date.getMinutes()).padStart(2, '0'); // 将分钟格式化为两位数
				// 	return `${hours}:${minutes}`;
				// });
				// console.log(timeArray.join(',')); // 输出 ["04:04", "04:04"]
			},
			init() {
				console.log(this.form)

				const imgStr1 = this.form.merchantSurfaceDrawing
				if (imgStr1.length) {
					if (imgStr1.includes(',')) {
						console.log('字符串中包含逗号');
						// 包含的进行slice(',') 分割

						this.imgStr1 = imgStr1.split(',').map((item) => item.trim());
						this.$refs.selectimgandupload1.setItems(this.imgStr1);
					} else {
						console.log('字符串中不包含逗号');
						this.imgStr1 = imgStr1.split();
						this.$refs.selectimgandupload1.setItems(this.imgStr1);
					}


				}
				const imgStr2 = this.form.merchantLogo
				if (imgStr2.length) {
					if (imgStr2.includes(',')) {
						console.log('字符串中包含逗号');
						// 包含的进行slice(',') 分割

						this.imgStr2 = imgStr2.split(',').map((item) => item.trim());
						this.$refs.selectimgandupload2.setItems(this.imgStr2);
					} else {
						console.log('字符串中不包含逗号');
						this.imgStr2 = imgStr2.split();
						this.$refs.selectimgandupload2.setItems(this.imgStr2);
					}


				}
				const imgStr3 = this.form.merchantDetailChart
				if (imgStr3.length) {
					if (imgStr3.includes(',')) {
						console.log('字符串中包含逗号');
						// 包含的进行slice(',') 分割

						this.imgStr3 = imgStr3.split(',').map((item) => item.trim());
						this.$refs.selectimgandupload3.setItems(this.imgStr3);
					} else {
						console.log('字符串中不包含逗号');
						this.imgStr3 = imgStr3.split();
						this.$refs.selectimgandupload3.setItems(this.imgStr3);
					}


				}


			},

			// “上传图片”发生改变
			imgsChange1(file) {
				// 文件名
				this.timeDate = new Date().getTime();
				console.log('上传发生改变this.storageMode11111============', this.storageMode, '参数file', file);
				// 如果是2 上传  阿里云 3  七牛云
				if (this.storageMode == 2) {
					this.userOssSignature(file);
				}
				if (this.storageMode == 3) {
					this.upPicUrl = this.$api.qnyOssSignature;
					let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
					this.imgFormData1 = {
						file: file,
						getsize: file.size,
						getContentType: ['image/png', 'image/jpeg'],
						getoriginalfilename: filesNmae,
						getName: filesNmae
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});
				}
			},
			imgsChange2(file) {
				// 文件名
				this.timeDate = new Date().getTime();
				console.log('上传发生改变this.storageMode22222============', this.storageMode, '参数file', file);
				// 如果是2 上传  阿里云 3  七牛云
				if (this.storageMode == 2) {
					this.userOssSignature(file);
				}
				if (this.storageMode == 3) {
					this.upPicUrl = this.$api.qnyOssSignature;
					let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
					this.imgFormData = {
						file: file,
						getsize: file.size,
						getContentType: ['image/png', 'image/jpeg'],
						getoriginalfilename: filesNmae,
						getName: filesNmae
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload2.upload(); //图片上传
					});
				}
			},
			imgsChange3(file) {
				// 文件名
				this.timeDate = new Date().getTime();
				console.log('上传发生改变this.storageMode333333============', this.storageMode, '参数file', file);
				// 如果是2 上传  阿里云 3  七牛云
				if (this.storageMode == 2) {
					this.userOssSignature(file,3);
				}
				if (this.storageMode == 3) {
					this.upPicUrl = this.$api.qnyOssSignature;
					let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
					this.imgFormData = {
						file: file,
						getsize: file.size,
						getContentType: ['image/png', 'image/jpeg'],
						getoriginalfilename: filesNmae,
						getName: filesNmae
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload3.upload(); //图片上传
					});
				}
			},
			// 阿里云上传
			async userOssSignature(file,index) {

				console.log('this阿里云上传进入=======');
				const ts = new Date().getTime();
				const us = {
					ts
				};
				let url = this.$api.alyOssSignature + `${object2Url(us)}`;
				const res = await this.$http.get({
					url: url,
					data: {
						us: us
					}
				});
				this.ossInfo = res.data;
				this.upPicUrl = this.ossInfo?.host;
				// 获取上传图片名称和后缀
				console.log(file)

				if (file.length) {
					let fileUrl = file[0].url;
					let markIndex = fileUrl.lastIndexOf('.');
					this.suffix = fileUrl.substring(markIndex); //后缀

					console.log('this.ossInfo', this.ossInfo);
					this.imgFormData = {
						name: this.timeDate + this.suffix,
						key: this.timeDate + this.suffix, //上传图片的名字和路径（默认路径根目录，自定义目录：xxx/xxx.png）
						policy: this.ossInfo.policy,
						OSSAccessKeyId: this.ossInfo.accessId,
						success_action_status: '200',
						signature: this.ossInfo.signature
					};
					this.header = {
						'Access-Control-Allow-Origin': '*',
						'x-oss-callback-Authorization': 'access_token'
					};
					this.$nextTick(() => {
						if(index==1){
							this.$refs.selectimgandupload1.upload()
						}else if(index==2){
							this.$refs.selectimgandupload2.upload()
						}else{
							this.$refs.selectimgandupload3.upload()
						}
						; //图片上传
					});
					console.log('页面阿里云url22222222222222', this.ossInfo?.host + '/' + this.timeDate + this.suffix);
				} else {
					this.imgStr = []
				}
              
			},

			// 上传图片返回
			imgLoaded1(e) {
				console.log('上传返回eeeee111============', e);
				try {
					this.img = [];
					for (let i = 0; i < e.length; i++) {

						this.img.push(e[i].url);
					}
				} catch (e) {
					this.img = [];
				}
				console.log('this.img=======', this.img);
				this.imgStr = this.img
				console.log(this.imgStr)
				this.form.merchantSurfaceDrawing = this.imgStr.length === 1 ? this.imgStr[0].toString() : this.imgStr
					.join(',');
			},
			imgLoaded2(e) {
				console.log('上传返回eeeee222============', e);
				try {
					this.img2 = [];
					for (let i = 0; i < e.length; i++) {
						this.img2.push(e[i].url);
					}
				} catch (e) {
					this.img2 = [];
				}

				this.imgStr = this.img2
				console.log(this.imgStr)
				this.form.merchantLogo = this.imgStr.length === 1 ? this.imgStr[0].toString() : this.imgStr
					.join(',');
			},
			imgLoaded3(e) {
				console.log('上传返回eeeee333============', e);
				try {
					this.img3 = [];
					for (let i = 0; i < e.length; i++) {
						this.img3.push(e[i].url);
					}
				} catch (e) {
					this.img3 = [];
				}

				this.imgStr = this.img3
				console.log(this.imgStr)
				this.form.merchantDetailChart = this.imgStr.length === 1 ? this.imgStr[0].toString() : this.imgStr
					.join(',');
			},

		}
	}
</script>

<style lang="less" scoped>
	page {
		background-color: #fff;
	}

	.card {
		padding: 30rpx;

		/deep/ .uni-easyinput__content {
			background-color: #fff !important;
		}

		.sumbit-btn {
			width: 670rpx;

			height: 100rpx;
			color: #fff;
			border-radius: 10px;
			background-color: #1890FF;
		}
	}
</style>